#region --- License & Copyright Notice ---
/*
Copyright (c) 2005-2011 Jeevan James
All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion

using System;
using System.IO;

using ConsoleFx;
using ConsoleFx.Programs.Simple;
using ConsoleFx.Validators;

using Id3.Info;
using Id3.Info.ChartLyrics;
using Id3.Info.LyrDb;

//FindLyrics <mp3 directory> -save:<directory>
//  -save: Saves the lyrics to the specified output directory

//FindLyrics <mp3 directory> -update [-language:<language>]
//  -update: Updates the mp3 file with the lyrics
//  -language: Specifies the language for the lyrics, default is eng

namespace Id3.Net.Samples.FindLyrics
{
    internal sealed class Program
    {
#pragma warning disable 649
        private static string _mp3Directory;
        private static string _outputDirectory;
#pragma warning restore 649

        private static int Main()
        {
            var app = new ConsoleProgram(Handler, includeHelpSupport: true);
            try
            {
                app.AddOption("save", "s", OptionRequirement.Required, expectedParameters: 1).ValidateWith(
                    new PathValidator(PathType.Directory, checkIfExists: false)).AssignTo(() => _outputDirectory);
                app.AddArgument().ValidateWith(new PathValidator(PathType.Directory)).AssignTo(() => _mp3Directory);
                return app.Run();
            }
            catch (Exception ex)
            {
                return app.HandleError(ex);
            }
        }

        public static int Handler()
        {
            string[] mp3Files = Directory.GetFiles(_mp3Directory, "*.mp3");

            InfoProvider chartLyricsProvider = new ChartLyricsInfoProvider();
            InfoProvider lyrDbLyricsProvider = new LyrDbInfoProvider();
            foreach (string mp3File in mp3Files)
            {
                Console.Write(Path.GetFileNameWithoutExtension(mp3File));

                Id3Tag tag;
                using (var mp3 = new Mp3File(mp3File))
                    tag = mp3.GetTag(Id3TagFamily.FileStartTag);
                if (tag == null)
                    continue;

                if (!tag.Artists.IsAssigned || !tag.Title.IsAssigned)
                {
                    Console.WriteLine();
                    continue;
                }

                Console.WriteLine(" ({0} - {1})", tag.Artists.Values[0], tag.Title.Value);

                Id3Tag[] lyricsTags = GetLyrics(tag, chartLyricsProvider, lyrDbLyricsProvider);
                if (lyricsTags == null || lyricsTags.Length == 0)
                    continue;

                string outputFilename = string.Format("{0} - {1}.txt", tag.Artists.Values[0], tag.Title.Value);
                string outputFile = Path.Combine(_outputDirectory, outputFilename);
                using (var lyricsWriter = new StreamWriter(outputFile, false))
                    lyricsWriter.Write(lyricsTags[0].Lyrics[0].Lyrics);

                Console.WriteLine("    {0}", outputFilename);
            }

            return 0;
        }

        private static Id3Tag[] GetLyrics(Id3Tag tag, params InfoProvider[] providers)
        {
            foreach (InfoProvider provider in providers)
            {
                Id3Tag[] lyricsTags;
                InfoProviderException exception = provider.TryGetInfo(tag, out lyricsTags);
                if (exception != null)
                    ConsoleEx.WriteLine(ConsoleColor.Red, null, exception.Message);
                else if (lyricsTags != null && lyricsTags.Length > 0)
                    return lyricsTags;
            }
            return null;
        }
    }
}